var video_handler;
var videoDeliveryUUID = [];

function InitVideoSetting() {
    var scene = viewer.scene;
    scene.shadowMap.darkness = 1.275; //设置第二重烘焙纹理的效果（明暗程度）
    scene.skyAtmosphere.brightnessShift = 0.4; //修改大气的亮度
    scene.debugShowFramesPerSecond = false;
    scene.hdrEnabled = false;
    scene.sun.show = false;
    return
    // 01设置环境光的强度-新处理CBD场景
    if (scene.lightSource)
        scene.lightSource.ambientLightColor = new Cesium.Color(0.65, 0.65, 0.65, 1);
    // 添加光源
    var position1 = new Cesium.Cartesian3.fromDegrees(110.46, 19.948, 480);
    //光源方向点
    var targetPosition1 = new Cesium.Cartesian3.fromDegrees(110.46, 19.948, 430);
    var dirLightOptions = {
        targetPosition: targetPosition1,
        color: new Cesium.Color(1.0, 1.0, 1.0, 1),
        intensity: 0.55
    };
    directionalLight_1 = new Cesium.DirectionalLight(position1, dirLightOptions);
    scene.addLightSource(directionalLight_1);
    var videoElement = document.getElementById('video_trailer');
    var projectionImage = new Cesium.ProjectionImage(scene);
    var handler = new Cesium.DrawHandler(viewer, Cesium.DrawMode.Point);
    handler.movingEvt.addEventListener(function(windowPosition) {
        //var last = viewer.scene.camera.pickEllipsoid(windowPosition,  viewer.scene.globe.ellipsoid);
        var last = scene.pickPosition(windowPosition);
        //计算该点与视口位置点坐标的距离
        var distance = Cesium.Cartesian3.distance(scene.camera.position, last);
        if (distance > 0) {
            //将鼠标当前点坐标转化成经纬度
            var cartographic = Cesium.Cartographic.fromCartesian(last);
            var longitude = Cesium.Math.toDegrees(cartographic.longitude);
            var latitude = Cesium.Math.toDegrees(cartographic.latitude);
            var height = cartographic.height;
            //通过该点设置视频投放对象的距离及方向
            projectionImage.setDistDirByPoint([longitude, latitude, height]);
            projectionImage.distance = Number($("#video_distance").val());
        }
    });

    //绘制裁剪面
    var handlerPolygon = new Cesium.DrawHandler(viewer, Cesium.DrawMode.Polygon, 0);
    handlerPolygon.drawEvt.addEventListener(function(result) {

        var array = [].concat(result.object.positions);
        var positions = [];
        for (var i = 0, len = array.length; i < len; i++) {

            var cartographic = Cesium.Cartographic.fromCartesian(array[i]);
            var longitude = Cesium.Math.toDegrees(cartographic.longitude);
            var latitude = Cesium.Math.toDegrees(cartographic.latitude);
            var h = cartographic.height;
            if (positions.indexOf(longitude) == -1 && positions.indexOf(latitude) == -1) {
                positions.push(longitude);
                positions.push(latitude);
                positions.push(h);
            }
        }
        handlerPolygon.polygon.show = false;
        handlerPolygon.polyline.show = false;
        projectionImage.addClipRegion({ name: 'test', position: positions });
        handlerPolygon.deactivate();
    });

    function clearAndActive() {
        projectionImage.distance = 0.1;
        var wgsPosition = scene.camera.positionCartographic;
        var longitude = Cesium.Math.toDegrees(wgsPosition.longitude);
        var latitude = Cesium.Math.toDegrees(wgsPosition.latitude);
        var height = wgsPosition.height;
        projectionImage.viewPosition = [longitude, latitude, height];
        projectionImage.horizontalFov = Number($("#video_horizontal").val());
        projectionImage.verticalFov = Number($("#video_vertical").val());
        projectionImage.direction = Number($("#video_direction").val());
        projectionImage.pitch = Number($("#video_pitch").val());
        projectionImage.setImage({
            video: videoElement
        });
        projectionImage.removeAllClipRegion ? projectionImage.removeAllClipRegion() : null;
        projectionImage.build();
    }
    $('#video_active').click(function(evt) {
        clearAndActive();
        handler.activate();
    });
    $('#video_clear').click(function(evt) {
        clearAndActive();
        handler.clear();
        handlerPolygon.clear();
    });
    $('#video_horizontal').bind('input propertychange', function() {
        var value = Number($(this).val());
        projectionImage.horizontalFov = value;
    });
    $('#video_vertical').bind('input propertychange', function() {
        var value = Number($(this).val());
        projectionImage.verticalFov = value;
    });
    $('#video_direction').bind('input propertychange', function() {
        var value = Number($(this).val());
        projectionImage.direction = value;
    });
    $('#video_pitch').bind('input propertychange', function() {
        var value = Number($(this).val());
        projectionImage.pitch = value;
    });
    $('#video_distance').bind('input propertychange', function() {
        var value = Number($(this).val());
        projectionImage.distance = value;
    });
    $('#visibleLine').on("input propertychange", function(evt) {
        projectionImage.hintLineVisible = $(this).prop("checked");
    });
    // $("#cilpRegion").click(function (e) {
    //     handlerPolygon.deactivate();
    //     handlerPolygon.activate();
    // });
    // $("#clip-mode").on("input propertychange", function () {
    //     clipMode = $(this).val() === 'clip-inside' ? Cesium.ModifyRegionMode.CLIP_INSIDE : Cesium.ModifyRegionMode.CLIP_OUTSIDE;
    //     projectionImage.setClipMode(clipMode);
    // });
}

function VideoDeliveryHandle() {
    tracker.trackPolygon(function(position) {
        var videoElement = document.createElement("video");
        // videoElement.setAttribute("id", "trailer");
        videoElement.setAttribute("autoplay", "true");
        videoElement.setAttribute("loop", "true");
        videoElement.setAttribute("crossorigin", "anonymous");
        // videoElement.setAttribute("crossorigin", "true");
        videoElement.setAttribute("controls", "true");
        videoElement.setAttribute("style", "display: none;-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);-ms-transform: rotate(45deg);-o-transform: rotate(45deg);transform: rotate(45deg);");
        var source = document.createElement("source");
        // source.setAttribute("src", $("#videoUrl").val());
        source.setAttribute("src", "http://localhost:8081/rtsp/live?rtspurl=" + encodeURIComponent($("#videoUrl").val()));
        source.setAttribute("type", $("#videoType").val());

        videoElement.appendChild(source);
        document.getElementById("mainBody").appendChild(videoElement);
        tracker.clear();
        var positions = [];
        for (var i = 0; i < position.length; i++) {
            var cartographic = Cesium.Cartographic.fromCartesian(position[i]);
            positions.push(Cesium.Math.toDegrees(cartographic.longitude));
            positions.push(Cesium.Math.toDegrees(cartographic.latitude));
            positions.push(cartographic.height);
        }
        var uuid = getUUID();
        var video = viewer.entities.add({
            id: "video_entity_" + uuid,
            name: 'video_entity_' + uuid,
            polygon: {
                //hierarchy: new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray(positions)),//平面
                hierarchy: new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArrayHeights(positions)), //高程
                classificationType: Cesium.ClassificationType.BOTH,
                clampToGround: true,
                material: videoElement
            }
        });
        videoDeliveryUUID.push(uuid);
        //viewer.zoomTo(video);
    });
}

function videoDeliveryClearHandle() {
    $.get("http://localhost:8081/rtsp/close", {}, function(data) {});
    for (var i = 0; i < videoDeliveryUUID.length; i++) {
        if (viewer.entities.getById("video_entity_" + videoDeliveryUUID[i])) {
            document.getElementById("mainBody").removeChild(viewer.entities.getById("video_entity_" + videoDeliveryUUID[i]).polygon.material.image.getValue());
            viewer.entities.removeById("video_entity_" + videoDeliveryUUID[i]);
        }
    }
    videoDeliveryUUID = [];
    setTimeout(function() {
        tracker && tracker.clear();
    }, 1000);
}